package com.qd.system.service.msg.server;

import com.cdqidi.util.SpringContextHolder;
import com.qd.common.sys.domain.entity.msg.MsgReceiveContentDTO;
import com.qd.common.sys.domain.sendmsg.FusionMsg;
import com.qd.common.sys.domain.sendmsg.MsgReceiver;
import com.qd.common.sys.domain.sendmsg.PersonMsg;
import com.qd.system.service.msg.event.SmsTemplateEvent;
import com.qd.system.service.msg.event.WxTemplateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息分发，选择通道，短信到短信通道、微信模板消息到微信通道
 * @author sjk
 */
@Component
@Slf4j
public class MsgDistributionService {

    public void sendFusionMsg(FusionMsg fusionMsg) {
        HashMap<String, PersonMsg> personMsgMap = new HashMap<>();
        try {
            for (MsgReceiver receive : fusionMsg.getMsgReceiver()) {
                build(receive.getId(), (short) receive.getClassify(), receive, personMsgMap, fusionMsg);
            }
            String url = null;
            if (fusionMsg.getMsgProperties().contains("appid")) {
                if (null != fusionMsg.getMsgProperties().getProp("pagepath")) {
                    url = fusionMsg.getMsgProperties().getProp("pagepath").toString();
                }
            } else {
                if (null != fusionMsg.getMsgProperties().getProp("WxTempUrl")) {
                    url = fusionMsg.getMsgProperties().getProp("WxTempUrl").toString();
                }
            }
            boolean hasUrl = StringUtils.hasLength(url);

            boolean urlhasparam = false;
            if (hasUrl) {
                urlhasparam = url.lastIndexOf('?') >= 0;
            }
            for (PersonMsg personMsg : personMsgMap.values()) {
                boolean hascustomurl = false;
                if (hasUrl) {
                    hascustomurl = true;
                    boolean hasparam = urlhasparam;
                    StringBuilder urlBuf = new StringBuilder();
                    urlBuf.append(url);

                    if (!personMsg.isEmptyUrlParams()) {
                        for (Map.Entry<String, String> entry : personMsg.getUrlParams().getProperties().entrySet()) {
                            if (hasparam) {
                                urlBuf.append("&");
                            } else {
                                urlBuf.append("?");
                                hasparam = true;
                            }
                            urlBuf.append(entry.getKey());
                            urlBuf.append("=");
                            urlBuf.append(entry.getValue());
                        }
                    }
                    personMsg.setUrl(urlBuf.toString());
                }

                if (hascustomurl || (personMsg.getMsgReceiveCustomProperties() != null) && !personMsg.getMsgReceiveCustomProperties().isEmpty()) {
                    MsgReceiveContentDTO msgReceiveContent = new MsgReceiveContentDTO();
                    if ((personMsg.getMsgReceiveCustomProperties() != null) && !personMsg.getMsgReceiveCustomProperties().isEmpty()) {
                        msgReceiveContent.setProp(personMsg.getMsgReceiveCustomProperties().toJson().toJSONString());
                    }
                    msgReceiveContent.setContentUrl(personMsg.getUrl());
                    msgReceiveContent.setContentDetail(fusionMsg.getMsgContent().getContent());
                    personMsg.setMsgReceiveContent(msgReceiveContent);
                }
            }
            for (PersonMsg personMsg : personMsgMap.values()) {

                if (personMsg.canSendWeixin()) {
                    SpringContextHolder.publishEvent(new WxTemplateEvent(personMsg));
                }
                if (personMsg.canSendSms()) {
                    SpringContextHolder.publishEvent(new SmsTemplateEvent(personMsg));
                }
            }
        } finally {
            personMsgMap.clear();
        }
    }

    private void build(String receiveId, short classify, MsgReceiver receiver, HashMap<String, PersonMsg> personMsgMap, FusionMsg fusionMsg) {
        PersonMsg personMsg = new PersonMsg();
        personMsg.setFromMsgId(fusionMsg.getFromMsgId());
        personMsg.setFromMsgSubId(fusionMsg.getFromMsgSubId());
        personMsg.setId(receiveId);
        personMsg.setClassify(classify);
        personMsg.setSendOrgId(fusionMsg.getSendOrgId());
        personMsg.setMsgContent(fusionMsg.getMsgContent());
        if (!receiver.isEmptyProperties()) {
            personMsg.setMsgReceiveCustomProperties(receiver.getProperties());
        }
        personMsg.setMsgProperties(fusionMsg.getMsgProperties());
        personMsg.setLevel(fusionMsg.getLevel());
        if (!receiver.isEmptyUrlParams()) {
            personMsg.setUrlParams(receiver.getUrlParams());
        }
        personMsg.setSendFlag(fusionMsg.getSendFlag());
        personMsg.setAppId(fusionMsg.getAppId());
        personMsgMap.put(personMsg.getId(), personMsg);
    }
}
